package Com.Ring.TradingMobile;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import Com.Ring.TradingMobile.Lib.Common;
import Com.Ring.TradingMobile.Lib.Common.MARKET;
import Com.Ring.TradingMobile.Object.CompanyInfo;
import Com.Ring.TradingMobile.Object.MarketInfo;
import Com.Ring.TradingMobile.Object.StockInfo;
import Com.Ring.TradingMobile.SQLite.DBManager;
import Com.Ring.TradingMobile.Service.WebService;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.widget.SlidingDrawer;
import android.widget.TextView;

public class ThiTruongTask implements Runnable {
	public ThiTruongActivity ThiTruong;
	private boolean IsUpdateCompany;
	private List<String> CodeArray;
	private String TAG = "ThiTruongTaskDebug";
	private boolean IsRealTime;
	private boolean IsSave;
	private int MarketId;
	private DBManager dbData;// = new DBManager(ThiTruong);

	public ThiTruongTask(ThiTruongActivity thiTruong, boolean isUpdateCompany,
			List<String> codeArray, MARKET marketEnum, boolean isRealTime,
			boolean isSave) {
		this.ThiTruong = thiTruong;
		this.IsUpdateCompany = isUpdateCompany;
		this.CodeArray = codeArray;
		this.IsRealTime = isRealTime;
		this.IsSave = isSave;
		this.MarketId = Common.ConvertToIntMarket(marketEnum);
		dbData = new DBManager(ThiTruong);
	}

	
	public void run() {
		
		if (IsUpdateCompany) {
			this.ThiTruong.ShowDialog();
			Log.d(TAG, "Running Update CompanyList");
			List<CompanyInfo> companyList = GetListCompany();
			try {
				Log.d(TAG, companyList.size() + "");
				this.ThiTruong.UpdateCompany(companyList);
				this.ThiTruong.IsUpdateCompany = false;
				if (IsSave)
					dbData.InsertCompanyList(companyList);
				Log.d(TAG, "Complete Update CompanyList");

			} catch (Exception ex) {
				Log.d(TAG, ex.toString());
			}
			this.ThiTruong.RemoveDialog();
		}
		if (this.CodeArray != null && this.CodeArray.size() > 0) {
			try {
				Log.d(TAG, "Running Update StockInfo");
				List<StockInfo> stockInfo = GetListStockInfo();
				this.ThiTruong.UpdateListStockInfo(stockInfo);
			} catch (Exception ex) {
				Log.d(TAG, ex.toString());
			}
		}
		// Update MarketInfo
		try {
			Log.d(TAG, "Running Update MarketInfo");
			MarketInfo marketInfo = GetMarketInfo();
			if (marketInfo != null) {
				this.ThiTruong.UpdateMarketInfo(marketInfo);
				if (IsSave)
					dbData.InsertMarketInfo(marketInfo);
			}
		} catch (Exception ex) {
			Log.d(TAG, ex.toString());
		}
		dbData.close();
	}

	private MarketInfo GetMarketInfo() {
		MarketInfo marketInfo = null;
		if (this.IsRealTime) {
			WebService service = new WebService();
			marketInfo = service.GetMarketInfoAndStatus(MarketId);
			dbData.InsertMarketInfo(marketInfo);
		} else {
			String sql = "select * from " + MarketInfo.TABLE_NAME
					+ " where _id = (select max(_id) from "
					+ MarketInfo.TABLE_NAME + " where " + MarketInfo.MARKET_ID
					+ " = " + this.MarketId + ")";
			Cursor cur = dbData.Select(sql);
			if (cur.getCount() > 0) {
				marketInfo = new MarketInfo();
				while (cur.moveToNext()) {
					marketInfo.marketid = this.MarketId;
					//marketInfo.CountFloor = cur.getFloat(cur
					//		.getColumnIndex(MarketInfo.COUNT_FLOOR));
					marketInfo.IndexChanged = cur.getFloat(cur
							.getColumnIndex(MarketInfo.INDEX_CHANGED));
					marketInfo.SetIndex = cur.getFloat(cur
							.getColumnIndex(MarketInfo.SET_INDEX));
					marketInfo.Status = cur.getString(cur
							.getColumnIndex(MarketInfo.STATUS));
					marketInfo.Time = cur.getInt(cur
							.getColumnIndex(MarketInfo.TIME));
					marketInfo.TotalShares = cur.getFloat(cur
							.getColumnIndex(MarketInfo.TOTAL_SHARES));
					marketInfo.TotalValues = cur.getFloat(cur
							.getColumnIndex(MarketInfo.TOTAL_VALUES));
					marketInfo.TradeDate = cur.getString(cur
							.getColumnIndex(MarketInfo.TRADE_DATE));
				}
			}
		}
		return marketInfo;
	}

	private List<CompanyInfo> GetListCompany() {
		WebService service = new WebService();
		List<CompanyInfo> companyList = service.GetCompanyList(1, 1);
		return companyList;
	}
	private List<StockInfo> GetListStockInfo() {
		List<StockInfo> listStockInfo = null;
		if (this.IsRealTime) {
			Log.d(TAG, "Get Data From Service");
			WebService service = new WebService();
			if (this.CodeArray.size() > 0) {
				String codes = CodeArray.get(0);
				for (int i = 1; i < CodeArray.size(); i++) {
					codes = codes + "," + CodeArray.get(i);
				}
				listStockInfo = service.GetListStockInfo(codes, 1);
				if (listStockInfo.size() > 0 && IsSave) {
					dbData.InsertStockInfoList(listStockInfo);
				}
			}
		} else {
			Log.d(TAG, "Get Data From Database");
			if (this.CodeArray.size() > 0) {
				StringBuilder whereArg = new StringBuilder();
				whereArg.append(StockInfo.SYMBOL);
				whereArg.append("='");
				whereArg.append(CodeArray.get(0));
				whereArg.append("'");
				for (int i = 1; i < CodeArray.size(); i++) {
					whereArg.append(" or ");
					whereArg.append(StockInfo.SYMBOL);
					whereArg.append("='");
					whereArg.append(CodeArray.get(i));
					whereArg.append("'");
				}
				// select max Trade_Date
				Cursor cur = dbData.Select("select " + StockInfo.TRADE_DATE
						+ " from " + StockInfo.TABLE_NAME
						+ " where _id = (select max(_id) from "
						+ StockInfo.TABLE_NAME + ") limit 1");
				if (cur.moveToNext()) {
					cur.getString(cur.getColumnIndex(StockInfo.TRADE_DATE));
					Log.d(TAG, cur.getString(cur
							.getColumnIndex(StockInfo.TRADE_DATE)));
					whereArg.append(" and ");
					whereArg.append(StockInfo.TRADE_DATE);
					whereArg.append("='");
					whereArg.append(cur.getString(0));
					whereArg.append("'");
				}

				String sql = String.format("select * from %s where %s ",
						StockInfo.TABLE_NAME, whereArg);
				Log.d(TAG, sql);
				Cursor listStockCursor = dbData.Select(sql);
				if (listStockCursor.getCount() > 0) {
					listStockInfo = new ArrayList<StockInfo>();
					while (listStockCursor.moveToNext()) {
						StockInfo stock = new StockInfo();
						stock.Symbol = listStockCursor
								.getString(listStockCursor
										.getColumnIndex(StockInfo.SYMBOL));
						stock.RefPrice = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.REF_PRICE));
						stock.CeilPrice = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.CEIL_PRICE));
						stock.FloorPrice = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.FLOOR_PRICE));
						stock.PriceMatch = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.PRICE_MATCH));
						stock.Changed = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.CHANGED));
						stock.PerChanged = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.PER_CHANGED));
						stock.VolumeMatch = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.VOLUME_MATCH));
						stock.TotalMatch = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.TOTAL_MATCH));

						stock.BestPriceBuy = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.BEST_PRICE_BUY));
						stock.BestVolbuy = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.BEST_VOL_BUY));
						stock.BestPriceSell = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.BEST_PRICE_SELL));
						stock.BestVolSell = listStockCursor
								.getFloat(listStockCursor
										.getColumnIndex(StockInfo.BEST_VOL_SELL));
						stock.TradeDate = listStockCursor
								.getString(listStockCursor
										.getColumnIndex(StockInfo.TRADE_DATE));
						listStockInfo.add(stock);
					}
				}
			}
		}
		return listStockInfo;

	}

}
